<?php
/**
 * FastApp.
 * 3/7/25
 * @Author deepsea
 * @Contact (telegram:deepsea159)
 */

namespace App\Hoenix\Api\Service;

use App\Fastapp\Api\Service\Telegram;
use App\Hoenix\Job\IndexKeywordJob;
use App\Hoenix\Job\TgChatInfoJob;
use App\Hoenix\Job\UserKeywordJob;
use App\Hoenix\Model\HoenixIndex;
use App\Hoenix\Model\HoenixKeyword;
use Telegram\Bot\Api;

class TgSearchBotService
{
    public static function skipBotMessage(): bool
    {
        return true;
    }

    public static function handle(array $data, Api $bot, int $bot_id): void
    {
        $message = '';
        $message_id = $data['message_id'];
        $reply_markup = $cmds = [];
        $text = $data['text'] ?? '';
        $appSetting = api_cache()->getAppSetting(redis()->hGet('bot:' . $bot_id, 'account_type'));
        if ($data['chat']['id'] == $appSetting['app_channel_index']) {
            self::channelPost($data, $bot, chatID: $data['chat']['id']);
            return;
        }
        if ($data['chat']['id'] == $appSetting['app_group_index']) {
            self::groupPost($text);
            return;
        }
        if (in_array($data['chat']['id'], explode(',', $appSetting['app_chat_search']))) {
            if ($text) list($message, $reply_markup) = self::getSearchTmp($data['from']['id'], $text, bot_id: $bot_id);
        } else {
            if (isset($data['entities'])) list($cmds, $text) = Telegram::parseEntity($data['entities'], $data['text']);
            if ($data['chat']['type'] == 'private') {
                $message_id = 0;
                if ($cmds) {
                    list($message, $reply_markup) = self::cmd($cmds[0], $text, $data['from'], $bot_id);
                    redis()->set('jis' . $data['from']['id'], $cmds[0], 300);
                } else {
                    if ($text) list($message, $reply_markup) = self::getSearchTmp($data['from']['id'], $text, bot_id: $bot_id, isPrivate: true);
                }
            } else {
                self::channelPost($data, $bot);
            }
        }

        if ($message || $reply_markup) {
            $parameters = [
                'chat_id' => $data['chat']['id'],
                'parse_mode' => 'HTML',
            ];
            if ($message_id) $parameters['reply_to_message_id'] = $message_id;
            if ($message) $parameters['text'] = $message;
            if ($reply_markup) $parameters['reply_markup'] = $reply_markup;
            $bot->sendMessage($parameters);
            if (!$cmds) fastapp_queue_push(new UserKeywordJob($text, $data['from']['id']), 'hoenix');
        }
    }

    public static function callbackQuery(array &$data, Api $bot, int $bot_id): void
    {
        if (str_starts_with($data['data'], 'u')) {
            @list($u, $tm, $cmd, $kw, $page, $cid) = explode('_', $data['data']);
            if ($cmd != 'kw') return;
            $tg_id = (int)substr($u, 1);
            list($message, $reply_markup) = self::getSearchTmp($tg_id, $kw, (int)$page, (int)$cid, $bot_id);
            if ($tg_id != $data['from']['id']) {
                $bot->answerCallbackQuery([
                    'callback_query_id' => $data['id'],
                    'text' => '⚠️ 这不是你的消息!',
                    'show_alert' => true
                ]);
                return;
            }
            if (time() - $tm > 86400) {
                $bot->answerCallbackQuery([
                    'callback_query_id' => $data['id'],
                    'text' => '⚠️ 消息已过期!',
                    'show_alert' => true
                ]);
                return;
            }
        } else {
            if ($data['data'] == 'close') {
                $bot->deleteMessage(['chat_id' => $data['message']['chat']['id'], 'message_id' => $data['message']['message_id']]);
                return;
            }
            if (!str_starts_with($data['data'], '/')) return;
            @list($cmd, $param) = explode('=', $data['data']);
            list($message, $reply_markup) = self::cmd($cmd, $param, $data['from'], $bot_id);
        }
        $edit = [
            'chat_id' => $data['message']['chat']['id'],
            'message_id' => $data['message']['message_id'],
            'parse_mode' => 'HTML',
        ];
        if ($message) $edit['text'] = $message;
        if ($reply_markup) $edit['reply_markup'] = $reply_markup;
        if ($message || $reply_markup) $bot->editMessageText($edit);
    }

    public static function getSearchTmp(int $tg_id, string $kw, int $page = 1, int $type = 0, int $bot_id = 0, bool $isPrivate = false): array
    {
        $res = SeedService::search($kw, $page, $type, ['⚠️ 搜索点正常内容呗', '']);
        if (!isset($res['list'])) return $res;
        $tp = [1 => '👥', 2 => '📢', 3 => '🎬', 4 => '🎵', 5 => '🖼', 6 => '📄', 7 => '🔗'];
        $totalPage = ceil($res['total'] / 15);
        if ($kw) $message[] = "关键词: <code>$kw</code>";
        else $message[] = "热门排行榜: ";
        $botConfig = redis()->hGetAll('bot:' . $bot_id);
        $appSetting = api_cache()->getAppSetting($botConfig['account_type']);
        if (!empty($appSetting['app_kf'])) {
            $message[] = "\n";
            $message[] = '<a href="' . $appSetting['app_kf'] . '">💡赞助位招商 👉🏻 点击联系客服 </a>';
        }
        $message[] = "\n";
        if ($res['list']) {
            foreach ($res['list'] as $item) {
//            tg://resolve?domain=tg&url=https://xxx //强制浏览器打开
                $row = [];
                $row[] = $tp[$item->type];
                if (in_array($item->type, [0, 1, 2, 7, 8])) $row[] = ' <a href="' . $item->url . '">';
                else $row[] = ' <a href="tg://resolve?domain=' . $item->username . '&post=' . $item->msg_id . '">';
                $row[] = $item->title;
                $row[] = '</a>';
                $message[] = implode('', $row);
            }
        }

        if (!$res['list'] && $page == 1) $message[] = "没有找到相关信息~~";
        if (!$res['list'] && $page > 1) $message[] = "没有更多信息了~~";
        if (!empty($appSetting['app_team'])) {
            $message[] = "";
            $message[] = $appSetting['app_team'];
            $message[] = $appSetting['app_team_desc'];
        }
        $message[] = "";
        if ($res['list']) $message[] = "第$page/{$totalPage}页";
        $message[] = "💡点击按钮可以切换类型👇";
        $tm = time();
        $typeBtn = [
            ['text' => $tp[1], 'callback_data' => "u{$tg_id}_{$tm}_kw_{$kw}_1_1"],
            ['text' => $tp[2], 'callback_data' => "u{$tg_id}_{$tm}_kw_{$kw}_1_2"],
            ['text' => $tp[3], 'callback_data' => "u{$tg_id}_{$tm}_kw_{$kw}_1_3"],
            ['text' => $tp[4], 'callback_data' => "u{$tg_id}_{$tm}_kw_{$kw}_1_4"],
            ['text' => $tp[5], 'callback_data' => "u{$tg_id}_{$tm}_kw_{$kw}_1_5"],
            ['text' => $tp[6], 'callback_data' => "u{$tg_id}_{$tm}_kw_{$kw}_1_6"],
            ['text' => $tp[7], 'callback_data' => "u{$tg_id}_{$tm}_kw_{$kw}_1_7"],
        ];
        if ($type) {
            $typeBtn = array_merge([['text' => '全部', 'callback_data' => "u{$tg_id}_{$tm}_kw_{$kw}_1_0"]], $typeBtn);
            unset($typeBtn[$type]);
            $typeBtn = array_values($typeBtn);
        }
        if ($page == 1) $prev = ['text' => '选妃就选凤凰阁 👉🏻', 'url' => $appSetting['app_hoenix']];
        else $prev = ['text' => '⬅️', 'callback_data' => "u{$tg_id}_{$tm}_kw_{$kw}_" . ($page - 1) . '_0'];
        $pageBtn[] = $prev;
        $pageBtn[] = ['text' => '➡️', 'callback_data' => "u{$tg_id}_{$tm}_kw_{$kw}_" . ($page + 1) . '_0'];
        $kb = [
            $typeBtn,
            $pageBtn,
        ];
        if ($isPrivate) {
            $kb[] = [
                ['text' => $botConfig['remark'] . '金点子', 'callback_data' => '/start=defi'],
                ['text' => $botConfig['remark'] . '交易宝', 'callback_data' => '/start=guarantee'],
            ];
            $kb[] = [
                ['text' => $botConfig['remark'] . '广点通', 'callback_data' => '/start=join'],
                ['text' => $botConfig['remark'] . '小彩页', 'callback_data' => '/start=ad'],
            ];
        } else {
            $kb[] = [
                ['text' => $botConfig['remark'] . '金点子', 'url' => $botConfig['link'] . '?start=defi'],
                ['text' => $botConfig['remark'] . '交易宝', 'url' => $botConfig['link'] . '?start=guarantee'],
            ];
            $kb[] = [
                ['text' => $botConfig['remark'] . '广点通', 'url' => $botConfig['link'] . '?start=join'],
                ['text' => $botConfig['remark'] . '小彩页', 'url' => $botConfig['link'] . '?start=ad'],
            ];
        }
        if ($page != 1) $kb[] = [['text' => '选妃就选凤凰阁 👉🏻', 'url' => $appSetting['app_hoenix']]];
        return [implode("\n", $message), json_encode(['inline_keyboard' => $kb], JSON_UNESCAPED_UNICODE)];
    }

    public static function cmd(string $cmd, ?string $param, ?array $from, int $bot_id): array
    {
        $message = $keyboard = [];
        $botConfig = redis()->hGetAll('bot:' . $bot_id);
        $appSetting = api_cache()->getAppSetting($botConfig['account_type']);
        if ($cmd == '/add') {
            if ($param) {
                $chat_username = null;
                if (str_contains($param, 'http')) {
                    $info = parse_url($param);
                    $chat_username = '@' . trim($info['path'], '/');
                } elseif (str_starts_with($param, '@')) {
                    $chat_username = trim($param);
                }
                if ($chat_username) {
                    $md = HoenixIndex::query()->where(['username' => $chat_username])
                        ->whereIn('type', [0, 1, 2])->first();
                    if ($md) $message[] = '⚠️收录信息已存在！'; else {
                        fastapp_queue_push(new TgChatInfoJob($bot_id, $chat_username), 'hoenix');
                        $message[] = '⚠️ 没有找到收录信息！';
                        $message[] = '💡邀请' . $botConfig['remark'] . '进您的群或频道并设置为管理员，则您的频道或群会被提交收录并提高排名。';
                        $keyboard = [
                            [
                                ['text' => '➕拉进群组', 'url' => $botConfig['link'] . '?startgroup'],
                                ['text' => '➕拉进频道', 'url' => $botConfig['link'] . '?startchannel'],
                            ]
                        ];
                    }
                }
            }
            if (!$message) {
                $message[] = '💡 请直接发送一个频道/群组/用户名';
                $message[] = "\n";
                $message[] = '示例：👇';
                $message[] = '<code>/add @' . basename($botConfig['link']) . '</code>';
                $message[] = '<code>/add ' . $botConfig['link'] . '</code>';
                $keyboard = [
                    [
                        ['text' => '❌关闭', 'callback_data' => 'close'],
                    ],
                ];
            }
        } elseif ($cmd == '/info') {
            if ($param) {
                $tp = [1 => '群组', 2 => '频道', 7 => '连接'];
                if (str_starts_with($param, '@')) $map = ['username' => $param];
                else $map = ['url' => $param];
                $md = HoenixIndex::query()->where($map)->first();
                if ($md) {
                    $message[] = 'ID：' . $md->id;
                    $message[] = 'Chat ID：' . $md->chat_id;
                    $message[] = '链接：' . $md->url;
                    $message[] = '类型：' . $tp[$md->type];
                    $message[] = '标题：' . $md->title;
                    if (in_array($md->type, [1, 2])) {
                        $message[] = '人数：' . $md->tgChat->num;
                        $message[] = '收录信息数：' . $md->msgNum->num;
                        $message[] = $md->tgChat->status ? '状态： ✅正常' : '状态：❌';
                    }
                    $message[] = '创建时间：' . $md->created_at;
                    $message[] = '收录时间：' . $md->c_at;
                    $message[] = '更新时间：' . $md->updated_at;
                    $keyboard = [
                        [
                            ['text' => '查看' . $tp[$md->type], 'url' => $md->url],
                            ['text' => '投诉举报', 'callback_data' => 'report_' . $md->id],
                        ],
                        [
                            ['text' => '❌关闭', 'callback_data' => 'close'],
                            ['text' => '↩️返回', 'callback_data' => '/start'],
                        ],
                    ];
                }
            }
            if (!$message) {
                $message[] = '💡 查询案例格式如下';
                $message[] = "\n";
                $message[] = '<code>/info @' . basename($botConfig['link']) . '</code>';
                $message[] = '<code>/info ' . $botConfig['link'] . '</code>';
                $keyboard = [
                    [
                        ['text' => '❌关闭', 'callback_data' => 'close'],
                    ],
                ];
            }
        } elseif ($cmd == '/start') {
            if ($param == 'defi') {
                $message[] = '质押';
            } elseif ($param == 'guarantee') {
                $message[] = '担保请联系<a href="' . $appSetting['app_kf'] . '">客服</a>';
            } elseif ($param == 'join') {
                $message[] = '加入请联系<a href="' . $appSetting['app_kf'] . '">客服</a>';
            } elseif ($param == 'ad') {
                $message[] = '投放广告请联系<a href="' . $appSetting['app_kf'] . '">客服</a>';
            } else {
                $message[] = '🔍 发送关键词来寻找群组、频道或视频。';
                $message[] = '❔ 查看帮助 👉 /help ';
                $message[] = '<a href="tg://setlanguage?lang=zhcncc">👉 点这里安装【简体中文】👈</a>';
            }
            $keyboard = [
                [
                    ['text' => '热门频道', 'callback_data' => '/hot_channel'],
                    ['text' => '热搜词', 'callback_data' => '/hot_keyword'],
                ],
                [
                    ['text' => '我的', 'callback_data' => '/my'],
                ],
                [
                    ['text' => '🇨🇳Telegram中文包', 'url' => 'tg://setlanguage?lang=zhcncc'],
                ],
                [
                    ['text' => '添加到群', 'switch_inline_query' => '快来试试' . $botConfig['remark'] . '吧！'],
                ],
            ];
        } elseif ($cmd == '/my') {
            $message[] = '用户ID： ' . $from['id'];
            $message[] = '昵称： ' . $from['username'];
            $keyboard = [
                [
                    ['text' => '🤝群组联盟', 'url' => $appSetting['app_group']],
                    ['text' => '🤝频道联盟', 'url' => $appSetting['app_group']],
                ],
                [
                    ['text' => '邀请好友', 'callback_data' => '/invite'],
                ],
                [
                    ['text' => '↩️返回', 'callback_data' => '/start'],
                ],
            ];
        } elseif ($cmd == '/hot_channel') {
            self::getSearchTmp($from['id'], '', 1, 2, $bot_id);
        } elseif ($cmd == '/hot_keyword') {
            $message[] = '热搜排行榜：';
            $kw = HoenixKeyword::query()->orderByDesc('num')->limit(24)->pluck('kw')->chunk(3)->toArray();
            if ($kw) {
                $tg_id = $from['id'];
                $tm = time();
                foreach ($kw as $item) {
                    $row = [];
                    foreach ($item as $keyword) {
                        $row[] = ['text' => $keyword, 'callback_data' => "u{$tg_id}_{$tm}_kw_{$keyword}_1_0"];
                    }
                    $keyboard[] = $row;
                }
                $keyboard[] = [
                    ['text' => '↩️返回', 'callback_data' => '/start'],
                ];
            }
        } else {
            $message[] = '欢迎使用 @' . basename($botConfig['link']);
            $message[] = "\n";
            $message[] = '🔍 ' . $botConfig['remark'] . '可以搜索Telegram群组、频道,甚至视频、音乐等资源';
            $message[] = "\n";
            $message[] = '👉 使用命令：';
            $message[] = '/start - 开始';
            $message[] = '/add - 添加链接到' . $botConfig['remark'];
            $message[] = '/info - 显示收录信息、投诉举报';
            $message[] = '/help - 帮助！';
            $keyboard = [
                [
                    ['text' => '加入' . $botConfig['remark'] . '官方群组', 'url' => $appSetting['app_group']],
                ],
                [
                    ['text' => '↩️返回', 'callback_data' => '/start'],
                ],
            ];
        }

        return [$message ? implode("\n", $message) : '', $keyboard ? json_encode([
            'inline_keyboard' => $keyboard
        ], JSON_UNESCAPED_UNICODE) : []];
    }

    public static function channelPost(array $data, ?Api $bot = null, ?int $chatID = null): void
    {
        if ($chatID) $data = array_merge($data, $data['forward_origin']);
        if (empty($data['chat']['username'])) return;
        $title = $desc = '';
        //0用户1群2频道3视频4音频5图片6文本7连接
        if (isset($data['photo'])) {
            $type = 5;
            if (!empty($data['caption'])) $title = $data['caption'];
            if (!empty($data['text'])) $desc = $data['text'];
        } elseif (isset($data['video'])) {
            $type = 3;
            if (!empty($data['caption'])) $title = $data['caption'];
            if (!empty($data['text'])) $desc = $data['text'];
        } elseif (isset($data['audio']) || isset($data['voice'])) {
            $type = 4;
            if (!empty($data['caption'])) $title = $data['caption'];
            if (!empty($data['text'])) $desc = $data['text'];
        } else {
            $type = 6;
            if (empty($data['caption'])) {
                $title = $data['text'];
            } else {
                $title = $data['caption'];
                $desc = $data['text'] ?? '';
            }
        }
        $map['chat_id'] = $data['chat']['id'];
        $map['msg_id'] = $data['message_id'];
        $map['type'] = $type;
        $map['title'] = $title;
        $map['desc'] = $desc;
        $map['username'] = $data['chat']['username'];

        fastapp_queue_push(new IndexKeywordJob($map), 'hoenix');
        $chat_id = $chatID ?: $data['chat']['id'];
        \swoole\Coroutine::create(function () use ($bot, $chat_id) {
            $res = $bot->sendMessage([
                'chat_id' => $chat_id,
                'text' => '信息已收录(5秒后自动删除)',
            ]);
            \swoole\Coroutine::sleep(5);
            $bot->deleteMessage(['chat_id' => $chat_id, 'message_id' => $res->messageId]);
        });
    }

    public static function init(Api $bot): void
    {
        $bot->deleteMyCommands();
        $commands = [
            ['command' => 'start', 'description' => '首页'],
            ['command' => 'my', 'description' => '我的'],
            ['command' => 'help', 'description' => '帮助'],
        ];
        $bot->setMyCommands(['commands' => $commands]);
    }

    public static function groupPost(string $txt): void
    {
        $data = json_decode($txt, true);
        $title = $desc = '';
        //0用户1群2频道3视频4音频5图片6文本7连接
        if (isset($data['photo'])) {
            $type = 5;
            if (!empty($data['caption'])) $title = $data['caption'];
            if (!empty($data['text'])) $desc = $data['text'];
        } elseif (isset($data['video'])) {
            $type = 3;
            if (!empty($data['caption'])) $title = $data['caption'];
            if (!empty($data['text'])) $desc = $data['text'];
        } elseif (isset($data['audio']) || isset($data['voice'])) {
            $type = 4;
            if (!empty($data['caption'])) $title = $data['caption'];
            if (!empty($data['text'])) $desc = $data['text'];
        } else {
            $type = 6;
            if (empty($data['caption'])) {
                $title = $data['text'];
            } else {
                $title = $data['caption'];
                $desc = $data['text'] ?? '';
            }
        }
        $map['chat_id'] = $data['chat']['id'];
        $map['msg_id'] = $data['message_id'];
        $map['type'] = $type;
        $map['title'] = $title;
        $map['desc'] = $desc;
        $map['username'] = $data['chat']['username'];

        fastapp_queue_push(new IndexKeywordJob($map), 'hoenix');
    }
}